<!-- 采购选择 -->
<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { getU8CHInfoAPI } from "@/api/api";
import { useConfig } from "@/store/modules/config";

const route = useRoute();
const selectedData = ref("");

const defaultProps = {
  children: "children",
  label: "label",
  value: "label",
};

const data = ref([]);
const loadData = async () => {
  // 选项数据
  // const res = await getU8CHInfoAPI()
  data.value = [
    {
      value: "option1",
      label: "选项 1",
      image: "https://via.placeholder.com/50",
    },
    {
      value: "option2",
      label: "选项 2",
      image: "https://via.placeholder.com/50",
    },
    {
      value: "option3",
      label: "选项 3",
      image: "https://via.placeholder.com/50",
    },
  ];
};

// 回显选项
const getApprovalSelectedItems = () => {
  wx.ready(() => {
    wx.invoke(
      "getApprovalSelectedItems",
      {
        key: route.query.key, // 字符串，从 URL 中获取到的 key
      },
      (res) => {
        if (res.err_msg === "getApprovalSelectedItems:ok") {
          // 获取成功，res.selectedData 为获取到的已选中选项的 JSON 字符串，注意可能为空。格式见下文。
          if (JSON.parse(res.selectedData)[0].value) {
            console.log(res.selectedData);

            selectedData.value = JSON.parse(res.selectedData)[0].value;
          }
        }
      }
    );
  });
};

// 选中
const handleNodeClick = async (e) => {
  wx.invoke(
    "saveApprovalSelectedItems",
    {
      key: route.query.key, // 字符串，从 URL 中获取到的 key
      selectedData: JSON.stringify([
        {
          key: "item-1",
          value: selectedData.value,
        },
      ]), // 字符串，选中的选项格式化为 JSON 字符串，格式见下文
    },
    (res) => {
      if (res.err_msg === "saveApprovalSelectedItems:ok") {
        // 保存成功
        console.log("成功");
      }
    }
  );
};

// 配置
const { config, agentConfig } = useConfig();

onMounted(async () => {
  await loadData();
  await config();
  // 先执行agentConfig再回显
  await agentConfig();
  getApprovalSelectedItems();
});
</script>

<template>
  <div>
    <el-select v-model="selected" placeholder="请选择" style="width: 200px">
      <template #dropdown>
        <div class="custom-dropdown">
          <el-option
            v-for="item in options"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          >
            <span class="option-label">{{ item.label }}</span>
            <img :src="item.image" class="option-image" alt="thumbnail" />
          </el-option>
        </div>
      </template>
    </el-select>
  </div>
</template>
